<template>
  <div>
    <el-upload
      ref="imgRef"
      class="upload"
      :headers="{
        Authorization: `Bearer ${$store.getters.token}`
      }"
      :action="httpUrl"
      multiple
      :limit="1"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :show-file-list="false"
    >
      <img v-if="imgUrl" :src="imgUrl" class="img" />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </div>
</template>
<script>
  import { localhostUrl } from '@/utils/setUrl.js'
  export default {
    props: {
      // 空值 占位符
      url: {
        type: String,
        default() {
          return ''
        }
      }
    },
    data() {
      return {
        imgUrl: '',
        // 获取图片地址
        httpUrl: `${localhostUrl}/Common/Upload`,
      }
    },
    watch: {
      url: function (newValue, oldValue) {
        this.imgUrl = newValue
      }
    },
    methods: {
      // 上传成功
      handleAvatarSuccess(res, file) {
        if (res.code === 200) {
          this.imgUrl = localhostUrl + '/' + res.data.url
          this.$emit('inputChange', this.imgUrl)
        }
        this.$refs.imgRef.clearFiles()
      },
      // 上传前
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
        // const isLt2M = file.size / 1024 / 1024 < 2

        if (!isJPG) {
          this.$message.error('上传图片只能是 JPG或PNG 格式!')
        }
        // if (!isLt2M) {
        //   this.$message.error('上传图片大小不能超过 2MB!')
        // }
        // return isJPG && isLt2M
        return isJPG
      },
    }
  }
</script>
<style lang="scss" scoped>
  .upload {
    width: 100px;
    height: 100px;
    border: 1px solid #ccc;
    display: flex;
    align-items: center;
    justify-content: center;
    /deep/.el-upload {
      width: 100% !important;
      height: 100% !important;
      display: flex;
      align-items: center;
      justify-content: center;
      .img {
        width: 100%;
        height: 100%;
      }
    }
  }
</style>
